﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.Shell.Implementation
{
    using System;
    using System.Collections.Generic;
    using System.Xml.Linq;

    /// <summary>
    /// Provides various useful extension methods.
    /// </summary>
    internal static class Extensions
    {

        /// <summary>
        /// Gets the value of an attribute with the specified name from the given element.
        /// </summary>
        /// <param name="element">The element from which to get the attribute.</param>
        /// <param name="attributeName">The name of the attribute to get.</param>
        /// <returns>The value of the attribute or a null reference if the attribute isn't defined.</returns>
        public static string GetAttributeValue(this XElement element, XName attributeName)
        {
            XAttribute attr = element.Attribute(attributeName);

            return attr == null ? null : attr.Value;
        }

        /// <summary>
        /// Gets the service of the given type.
        /// </summary>
        /// <typeparam name="T">The type of the service to get.</typeparam>
        /// <param name="this">The service provider from which to get the service.</param>
        /// <returns></returns>
        public static T GetService<T>(this IServiceProvider @this)
        {
            return (T)@this.GetService(typeof(T));
        }

        /// <summary>
        /// Gets the value with the given key, or the default value for the type if no
        /// matching key is found.
        /// </summary>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="this">The dictionary from which to get the value.</param>
        /// <param name="key">The key which identifies the value to get.</param>
        /// <returns>The matching result or the default value for the result type.</returns>
        public static TResult ItemOrDefault<TKey, TResult>(this IDictionary<TKey, TResult> @this, TKey key)
        {
            TResult result;

            // Automatically sets result to default(TResult)
            // if the lookup fails
            @this.TryGetValue(key, out result);

            return result;
        }
    }
}
